package com.jz.digital.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Looper;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jz.digital.MyAppLocation;
import com.jz.digital.R;

/**
 * @author WangYong
 * @date 2024/11/28 15:53
 * @description:
 */
public class ToastUtils {
    private static ToastUtils instance;
    private Toast mToast;

    private ToastUtils() {

    }

    // 获取单例实例
    public static synchronized ToastUtils getInstance() {
        if (instance == null) {
            instance = new ToastUtils();
        }
        return instance;
    }


    /**
     * 弹出一个toast
     *
     * @param msg 字符串资源
     */
    public void showToast(String msg) {
        showToast(msg, Toast.LENGTH_SHORT);
    }

    /**
     * 正常显示 Toast
     *
     * @param text
     * @param duration
     */
    @SuppressLint("WrongConstant")
    public void showToast(String text, int duration) {
        if (TextUtils.isEmpty(text) || Thread.currentThread() != Looper.getMainLooper().getThread())
            return;
        if (duration == Toast.LENGTH_SHORT) {
            duration = 1000;
        } else if (duration == Toast.LENGTH_LONG) {
            duration = 2000;
        } else {
            if (duration < 1000) {
                duration = 1000;
            }
        }

        if (mToast == null) {
            mToast = getToast(text, duration);
        } else {
            mToast.cancel();
            TextView loading_msg = mToast.getView().findViewById(R.id.txt_normal_tips);
            if (loading_msg != null)
                loading_msg.setText(text);
        }
        /*if (manualDismiss) mToast.setDuration(Toast.LENGTH_LONG);
        else*/
        mToast.setDuration(duration);
        mToast.show();
    }

    private Toast getToast(String text, int duration) {
        Toast toast = new Toast(MyAppLocation.mContext);
        LayoutInflater inflate = (LayoutInflater) MyAppLocation.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(R.layout.layout_normal_toast, null);
        TextView loading_msg = v.findViewById(R.id.txt_normal_tips);
        loading_msg.setText(text);
        toast.setView(v);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(duration);
        return toast;
    }
}
